package org.xx.armory.swing.components;

import javax.swing.*;
import java.awt.*;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 由多个按钮组成的条。
 */
public class ButtonBar
        extends JPanel {
    private Map<String, Action> actions;

    public ButtonBar() {
        this.actions = new LinkedHashMap<>();
        initUi();
    }

    protected void initUi() {
        final FlowLayout layout = new FlowLayout();
        // 默认水平右对齐，垂直基线对齐。
        layout.setAlignment(FlowLayout.TRAILING);
        layout.setAlignOnBaseline(true);
        this.setLayout(layout);
    }

    public Map<String, Action> getActions(
    ) {
        return this.actions;
    }

    public void setActions(
            Map<String, ? extends Action> actions
    ) {
        if (actions == null) {
            actions = Collections.emptyMap();
        }

        firePropertyChange("actions", this.actions, actions);

        this.actions.clear();
        this.actions.putAll(actions);

        updateActions();
    }

    protected void updateActions() {
        this.removeAll();
        for (final Map.Entry<String, Action> entry : this.actions.entrySet()) {
            final String name = entry.getKey();
            final Action action = entry.getValue();
            if (action != null) {
                final JButton button = new JButton();
                button.setAction(entry.getValue());
                this.add(name, button);
            } else {
                final JLabel placeholder = new JLabel();
                placeholder.setText(" ");
                this.add(name, placeholder);
            }
        }
    }

    public int getPadding() {
        final FlowLayout layout = (FlowLayout) this.getLayout();
        return layout.getVgap();
    }

    public void setPadding(
            int padding
    ) {
        final FlowLayout layout = (FlowLayout) this.getLayout();
        layout.setHgap(padding);
        layout.setVgap(padding);
    }
}
